const api = require('../../utils/api.js');
const app = getApp();

Page({
  data: {
    address_list: null,
  },

  onLoad() {
    app.pageOnLoad(this);
  },

  onShow() {
    let that = this;
    wx.showNavigationBarLoading();
    app.ws_micro_shoprequest({
      url: api.user.address_list,
      success: function(res) {
        wx.hideNavigationBarLoading();
        if (res.code === 0) {
          that.setData({
            address_list: res.data.list,
          });
        }
      },
    });
  },

  pickAddress(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let address = that.data.address_list[index];
    wx.setStorageSync('picker_address', address);
    wx.navigateBack();
  },

  getWechatAddress() {
    wx.chooseAddress({
      success: function(e) {
        if (e.errMsg !== 'chooseAddress:ok') {
          return;
        }
        wx.showLoading();
        app.ws_micro_shoprequest({
          url: api.user.add_wechat_address,
          method: 'post',
          data: {
            national_code: e.nationalCode,
            name: e.userName,
            mobile: e.telNumber,
            detail: e.detailInfo,
            province_name: e.provinceName,
            city_name: e.cityName,
            county_name: e.countyName,
          },
          success: function(res) {
            if (res.code === 1) {
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
              });
              return;
            }
            if (res.code === 0) {
              wx.setStorageSync('picker_address', res.data);
              wx.navigateBack();
            }
          },
          complete: function() {
            wx.hideLoading();
          },
        });
      },
    });
  },
});
